package yesjava;

import java.io.*;

public class MyUtils {

    public static Object deepClone(Object object) {
        Object rs = null;
        ByteArrayOutputStream arrayOutputStream = null;
        ObjectOutputStream oos = null;
        InputStream in = null;
        ObjectInputStream objectInputStream = null;
        try {
            arrayOutputStream = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(arrayOutputStream);
            oos.writeObject(object);
            oos.flush();
            in = new ByteArrayInputStream(arrayOutputStream.toByteArray());
            objectInputStream = new ObjectInputStream(in);
            rs = objectInputStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (arrayOutputStream != null) try {
                arrayOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return rs;
    }


    public static Object deepCloneByDisk(Object object) {
        ObjectInputStream in = null;
        ObjectOutputStream out = null;
        File file = new File("./temp");
        try {
            out = new ObjectOutputStream(new FileOutputStream(file));
            in = new ObjectInputStream(new FileInputStream(file));
            out.writeObject(object);
            return (Object) in.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (in != null) try {
                in.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            if (out != null) try {
                out.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            if (file.exists()) {
                file.delete();
            }
        }
    }
}
